package com.dzt.androidframework.database.tasks;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.dzt.androidframework.R;
import com.dzt.androidframework.constant.AppConstant;
import com.dzt.androidframework.database.addedittask.AddEditActivity;
import com.dzt.androidframework.database.javabean.Task;
import com.dzt.androidframework.database.taskdetail.TaskDetailActivity;
import com.dzt.androidframework.fragment.FragmentBase;
import com.dzt.androidframework.utils.JLogKit;
import com.dzt.androidframework.widgets.ScrollChildSwipeRefreshLayout;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by M02323 on 2017/6/10.
 */

@ContentView(R.layout.fragment_tasks)
public class TasksFragment extends FragmentBase implements TasksContract.View {

	private TasksContract.Presenter presenter;
	private TasksAdapter adapter;
	@ViewInject(R.id.noTasks)
	private View mNoTasksView;  //无任务时显示的界面，有任务隐藏
	@ViewInject(R.id.noTasksIcon)
	private ImageView mNoTaskIcon;  //无任务显示的图标
	@ViewInject(R.id.noTasksMain)
	private TextView mNoTaskMainView;  //无任务时显示的文字提示
	@ViewInject(R.id.noTasksAdd)
	private TextView mNoTaskAddView;   //暂时隐藏
	@ViewInject(R.id.filteringLabel)
	private TextView mFilteringLabelView;  //过滤类型提示
	@ViewInject(R.id.tasks_list)
	private ListView listView;   //显示任务列表，无任务隐藏
	@ViewInject(R.id.refresh_layout)
	private ScrollChildSwipeRefreshLayout swipeRefreshLayout;

	@Override
	protected void initWidgets() {
		FloatingActionButton fab =
				(FloatingActionButton) getActivity().findViewById(R.id.fab);
		fab.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				presenter.addNewTask();
			}
		});
		adapter = new TasksAdapter(context, new ArrayList<Task>(0), mItemListener);
		listView.setAdapter(adapter);
		swipeRefreshLayout.setColorSchemeColors(
				ContextCompat.getColor(getActivity(), R.color.colorPrimary),
				ContextCompat.getColor(getActivity(), R.color.colorAccent),
				ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark)
		);
		// Set the scrolling view in the custom SwipeRefreshLayout.
		swipeRefreshLayout.setScrollUpChild(listView);
		swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				//下拉刷新
				presenter.loadTasks(false);
			}
		});
		presenter.start();
	}

	@Event(value = {R.id.noTasksAdd, R.id.btn_clear_completed_task, R.id.btn_menu})
	private void onClickView(View view) {
		switch (view.getId()) {
			case R.id.noTasksAdd:
				showAddTask();
				break;
			case R.id.btn_clear_completed_task:
				presenter.clearCompletedTasks();
				break;
			case R.id.btn_menu:
				showFilteringPopUpMenu(getActivity(), view);
				break;
			default:
				break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		presenter.result(requestCode, resultCode);
	}

	/**
	 * Listener for clicks on tasks in the ListView.
	 */
	TasksAdapter.TaskItemListener mItemListener = new TasksAdapter.TaskItemListener() {
		@Override
		public void onTaskClick(Task clickedTask) {
			presenter.openTaskDetails(clickedTask);
		}

		@Override
		public void onCompleteTaskClick(Task completedTask) {
			presenter.completeTask(completedTask);
		}

		@Override
		public void onActivateTaskClick(Task activatedTask) {
			presenter.activateTask(activatedTask);
		}
	};

	@Override
	public void setPresenter(TasksContract.Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public void setLoadingIndicator(final boolean active) {
		if (getView() == null) {
			return;
		}

		// Make sure setRefreshing() is called after the layout is done with everything else.
		swipeRefreshLayout.post(new Runnable() {
			@Override
			public void run() {
				swipeRefreshLayout.setRefreshing(active);
			}
		});
	}

	@Override
	public void reLoadTask() {
		presenter.loadTasks(false);
	}

	@Override
	public void showTasks(List<Task> tasks) {
		if (adapter == null) {
			JLogKit.getInstance().i("showTasks adapter == null");
		}
		adapter.replaceData(tasks);
		listView.setVisibility(View.VISIBLE);
		mNoTasksView.setVisibility(View.GONE);
	}

	@Override
	public void showAddTask() {
		Intent intent = new Intent(getContext(), AddEditActivity.class);
		startActivityForResult(intent, AppConstant.REQUEST_ADD_TASK);
	}

	@Override
	public void showTaskDetailsUi(String taskId) {
		Intent intent = new Intent(getContext(), TaskDetailActivity.class);
		intent.putExtra(TaskDetailActivity.EXTRA_TASK_ID, taskId);
		startActivityForResult(intent, AppConstant.REQUEST_DETAIL_TASK);
	}

	@Override
	public void showTaskMarkedComplete() {
		showToast("任务标记为完成");
	}

	@Override
	public void showTaskMarkedActive() {
		showToast("任务已被激活");
	}

	@Override
	public void showCompletedTasksCleared() {
		showToast("完成的任务已被清除");
	}

	@Override
	public void showLoadingTasksError() {
		showToast("加载任务失败");
		swipeRefreshLayout.post(new Runnable() {
			@Override
			public void run() {
				swipeRefreshLayout.setRefreshing(false);
			}
		});
	}

	@Override
	public void showNoTasks() {
		showNoTasksViews(
				getResources().getString(R.string.no_tasks_all),
				R.drawable.ic_assignment_turned_in_24dp, false
		);
	}

	@Override
	public void showActiveFilterLabel() {
		mFilteringLabelView.setText(getResources().getString(R.string.label_active));
	}

	@Override
	public void showCompletedFilterLabel() {
		mFilteringLabelView.setText(getResources().getString(R.string.label_completed));
	}

	@Override
	public void showAllFilterLabel() {
		mFilteringLabelView.setText(getResources().getString(R.string.label_all));
	}

	@Override
	public void showNoActiveTasks() {
		showNoTasksViews(
				getResources().getString(R.string.no_tasks_active),
				R.drawable.ic_check_circle_24dp, false
		);
	}

	@Override
	public void showNoCompletedTasks() {
		showNoTasksViews(
				getResources().getString(R.string.no_tasks_completed),
				R.drawable.ic_verified_user_24dp, false
		);
	}

	private void showNoTasksViews(String mainText, int iconRes, boolean showAddView) {
		listView.setVisibility(View.GONE);
		mNoTasksView.setVisibility(View.VISIBLE);

		mNoTaskMainView.setText(mainText);
		mNoTaskIcon.setImageDrawable(ContextCompat.getDrawable(getContext(), iconRes));
		mNoTaskAddView.setVisibility(showAddView ? View.VISIBLE : View.GONE);
	}

	@Override
	public void showSuccessfullySavedMessage() {
		showToast("保存成功");
	}

	@Override
	public boolean isActive() {
		return isAdded();
	}

	@Override
	public void showFilteringPopUpMenu(final Context context, View view) {
		//弹出过虑菜单
		PopupMenu popup = new PopupMenu(context, view);
		popup.inflate(R.menu.filter_tasks);

		popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				switch (item.getItemId()) {
					case R.id.active:
						presenter.setFiltering(TasksFilterType.ACTIVE_TASKS);
						break;
					case R.id.completed:
						presenter.setFiltering(TasksFilterType.COMPLETED_TASKS);
						break;
					default:
						presenter.setFiltering(TasksFilterType.ALL_TASKS);
						break;
				}
				presenter.loadTasks(false);
				return true;
			}
		});
		popup.show();
	}
}
